#!/usr/bin/python2.4
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import pwd
import sys

import gvn
import svn.fs
import svn.repos


def usage():
  sys.stderr.write('\nusage: sudo -u www-data change-rev-prop [--doit]'
                   ' REPO REVISION REVPROP VALUE\n'
                   '       change-rev-prop [--doit] --remove'
                   ' REPO REVISION REVPROP\n')
  sys.exit(2)

def main(argv):
  # if you were to run this as root, it would create new files in the repository
  # as root that may not be accessible/modifiable by www-data.
  if pwd.getpwuid(os.geteuid())[0] != 'www-data':
    sys.stderr.write("You MUST run as www-data or it'll break the repository\n")
    usage()
  if len(argv) < 5:
    usage()
  if argv[1] == '--doit':
    doit = True
    args = argv[2:]
  else:
    doit = False
    args = argv[1:]
  if len(args) != 4:
    usage()
  if args[0] == '--remove':
    (_, repo, revision, revprop) = args
    revision = int(revision)
    value = None
    sys.stderr.write('remove %s from %d in %s\n' % (revprop, revision, repo))
  else:
    (repo, revision, revprop, value) = args
    revision = int(revision)
    sys.stderr.write('set %s on %d in %s to """%s"""\n'
                     % (revprop, revision, repo, value))

  if doit:
    fs = svn.repos.fs(svn.repos.open(repo))
    svn.fs.change_rev_prop(fs, revision, revprop, value)
  else:
    sys.stderr.write('use --doit to really do this\n')
  return 0

if __name__ == '__main__':
  sys.exit(main(sys.argv))
